//
//  HKProgressView.m
//  HKUtilities
//
//  Created by 胡锦涛 on 2018/11/14.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

#import "HKProgressView.h"
#import "HKResultMessage.h"
#import "HKPrefixHeader.h"
@interface HKProgressView()
@property (nonatomic, copy)HKOnClickBlock retryBlock;
@end
@implementation HKProgressView
{
    UIImageView *aniView;
    UIImageView *logoView;
    UILabel *labelView;
}

+ (HKProgressView *)sharedInstance
{
    static dispatch_once_t  onceToken;
    static HKProgressView * _sharedInstance;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[HKProgressView alloc] init];
    });
    return _sharedInstance;
}

- (id)init
{
    if (self=[super init]) {
        CGRect rect = [HKScale vRect];
        [self setFrame:rect];
        [self setBackgroundColor:[UIColor whiteColor]];
        
        logoView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 261*suitScale, 249*suitScale)];
        logoView.image = [UIImage imageNamed:@"断网"];
        [self addSubview:logoView];
        
        aniView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 375*suitScale, 555*suitScale)];
        NSMutableArray *a = @[].mutableCopy;
        for (int i =0; i<4; i++) {
            [a addObject:[UIImage imageNamed:[NSString stringWithFormat:@"加载－%d",i+1]]];
        }
        aniView.animationImages = a;
        aniView.animationDuration = 0.5f;
        [self addSubview:aniView];
        
        rect.origin.x=40*gScale;
        rect.size.width=uiSize.width-rect.origin.x*2;
        rect.size.height=100*gScale;
        rect.origin.y=0;
        labelView = [[UILabel alloc] initWithFrame:rect];
        UIColor *textColor = HKHexColor(0xFFCDCDCD);
        [labelView setTextColor:textColor];
        [labelView setFont:[UIFont systemFontOfSize:44*gScale]];
        [labelView setTextAlignment:NSTextAlignmentCenter];
        [labelView setLineBreakMode:NSLineBreakByWordWrapping];
        [labelView setNumberOfLines:0];
        [labelView setHidden:YES];
        [self addSubview:labelView];
    }
    return self;
}

- (void)addTo:(UIView *)parent
{
    [self removeFromSuperview];
    CGRect rect = [parent bounds];
    rect.origin = CGPointZero;
    [self setFrame:rect];
    rect.origin.x=rect.size.width/2;
    rect.origin.y=(rect.size.height)/2;
    [aniView setCenter:rect.origin];
    [logoView setCenter:rect.origin];
    [labelView setCenter:rect.origin];
    logoView.centerY -= labelView.height;
    labelView.top = logoView.bottom + 40*gScale;
    [aniView setHidden:NO];
    [logoView setHidden:YES];
    [labelView setHidden:YES];
    [parent addSubview:self];
    [self startAnimating];
}


- (void)showErrorMessage:(NSString *)message WithRetry:(HKOnClickBlock)retryBlock
{
    _retryBlock = retryBlock;
    [self stopAnimating];
    [aniView setHidden:YES];
    
    [logoView setHidden:NO];
    [labelView setText:message];
    [labelView setHidden:NO];
}

- (BOOL)showErrorMessage:(HKResultMessage *)result OnRetry:(HKOnClickBlock)retryBlock{
    
    if (!result) {
        return NO;
    }
    NSString *messageText = nil;
    if ([result errorCode]) {
        if ([result netCode]) {
            if ([result netCode] == 403) {
                messageText = @"未登录或登录失效";
            }else{
                messageText = [NSString stringWithFormat:@"网络连接错误:%d%@", (int)[result netCode], HK_RETRY_MSG];
            }
        } else {
            switch ([result errorCode]) {
                    case HKServiceErrorUrlOrFileNotFound:
                    messageText = [NSString stringWithFormat:@"网络地址错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorCantParse:
                    messageText = [NSString stringWithFormat:@"从服务端加载的数据数据错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorServer:
                    messageText = [NSString stringWithFormat:@"连接服务器时发生错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorNetwork:
                    messageText = [NSString stringWithFormat:@"当前没有网络%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorParse:
                    messageText = [NSString stringWithFormat:@"解析数据时发生错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorNotLogin:
                    messageText = @"未登录或登录失效";
                    break;
                    case HKServiceErrorNetworkButUseCache:
                    messageText = @"当前没有网络，现在显示的是缓存内容";
                    //[HKToast showWithText:messageText];
                    return NO;
                default:
                    messageText = [NSString stringWithFormat:@"发生未知错误:%d%@", (int)[result errorCode], HK_RETRY_MSG];
                    break;
            }
            messageText = [NSString stringWithFormat:@"网络连接失败，请检查网络...%@",HK_RETRY_MSG];
        }
    } else {
        if ([result result]) {
            if (result.message.length) {
                messageText = [NSString stringWithFormat:@"%@%@",[result message], HK_RETRY_MSG];
            }else{
                messageText = [NSString stringWithFormat:@"网络连接失败，请检查网络...%@",HK_RETRY_MSG];
            }
        }
    }
    if (messageText) {
        [self showErrorMessage:messageText WithRetry:retryBlock];
        return YES;
    }
    return NO;
    
}

/**
 * 返回YES表示有错误发生，会显示错误信息并等待用户处理
 * 返回NO表示没有错误，继续进行其他操作
 */
+ (BOOL)showErrorMessage:(HKResultMessage *)result OnRetry:(HKOnClickBlock)retryBlock
{
    if (!result) {
        return NO;
    }
    NSString *messageText = nil;
    if ([result errorCode]) {
        if ([result netCode]) {
            if ([result netCode] == 403) {
                messageText = @"未登录或登录失效";
            }else{
                messageText = [NSString stringWithFormat:@"网络连接错误:%d%@", (int)[result netCode], HK_RETRY_MSG];
            }
        } else {
            switch ([result errorCode]) {
                    case HKServiceErrorUrlOrFileNotFound:
                    messageText = [NSString stringWithFormat:@"网络地址错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorCantParse:
                    messageText = [NSString stringWithFormat:@"从服务端加载的数据数据错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorServer:
                    messageText = [NSString stringWithFormat:@"连接服务器时发生错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorNetwork:
                    messageText = [NSString stringWithFormat:@"当前没有网络%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorParse:
                    messageText = [NSString stringWithFormat:@"解析数据时发生错误%@",HK_RETRY_MSG];
                    break;
                    case HKServiceErrorNotLogin:
                    messageText = @"未登录或登录失效";
                    break;
                    case HKServiceErrorNetworkButUseCache:
                    messageText = @"当前没有网络，现在显示的是缓存内容";
                    return NO;
                default:
                    messageText = [NSString stringWithFormat:@"发生未知错误:%d%@", (int)[result errorCode], HK_RETRY_MSG];
                    break;
            }
            messageText = [NSString stringWithFormat:@"网络连接失败，请检查网络...%@",HK_RETRY_MSG];
        }
    } else {
        if ([result result]) {
            messageText = result.message;
        }
    }
    if (messageText) {
        [[HKProgressView sharedInstance] showErrorMessage:messageText WithRetry:retryBlock];
        return YES;
    }
    return NO;
}

+ (void)dismiss
{
    [[HKProgressView sharedInstance] dismiss];
}

- (void)startAnimating
{
    [aniView startAnimating];
}

- (void)stopAnimating
{
    [aniView stopAnimating];
}

- (void)dismiss
{
    [self stopAnimating];
    [self removeFromSuperview];
}

#pragma ---- Touch Event ----
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_retryBlock) {
        _retryBlock();
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
{
}

@end
